//
//  WbHomeViewModel.swift
//  Weibo
//
//  Created by HH on 16/12/4.
//  Copyright © 2016年 Weibo. All rights reserved.
//

import UIKit
import SDWebImage

class WbHomeViewModel: NSObject {
    
    static let sharedHomeViewModel = WbHomeViewModel()
    
    var statuesList:[WbStatusesViewModel] = [WbStatusesViewModel]()

}

extension WbHomeViewModel{
    //MARK:获取用户关注的微博
    func loadRequestStatuses_friends_timeline(isPullUp:Bool ,complete:@escaping (Bool,String)->()){
        
        //获取since_id之后的微博
        var since_id:Int64 = 0
        //获取max_id之前的微博
        var max_id:Int64 = 0
       
        
        //获取老微博
        if isPullUp {
            
            max_id = self.statuesList.last?.statuses?.id ?? 0
            
            if max_id > 0 {
                max_id -= 1
            }
        }else{
            //获取最新微博
            since_id = self.statuesList.first?.statuses?.id ?? 0
            
        }
        
        WbNetworking.sharedTools.requestStatuses_friends_timeline(since_id:since_id,max_id:max_id ) { (response, error) in
            print(since_id,max_id)
            if error != nil{
                print("获取用户关注微博失败")
                print(error!)
                
                return
            }
            
//            print(response!)
            
            let dict = response as! [String:Any]
            
            let statusesArray = dict["statuses"]
            
//                        print(statusesArray!)
            let tempArray:[WbStatusesModel] = NSArray.yy_modelArray(with: WbStatusesModel.self, json: statusesArray!) as! [WbStatusesModel]
            
            
            var modelArr:[WbStatusesViewModel] = [WbStatusesViewModel]()
            
            //将数据转换成StatusesViewModel来处理
            for model in tempArray{
                
                let viewModel = WbStatusesViewModel()
                
                viewModel.statuses = model
                
               modelArr.append(viewModel)
            
            }
            
            
            
            
            //将每一个下载图片的造作都放入调度组当中
            let group = DispatchGroup()
            
            //下载单张图片为了之后处理
            for model in modelArr{
                
                //判断原创微博配图的个数
                if model.statuses?.pic_urls?.count == 1{
                    
                    if let imageUrl = model.statuses?.pic_urls?.first?.thumbnail_pic {
                        
                        group.enter()
                        
                        SDWebImageManager.shared().downloadImage(with: URL(string:imageUrl), options: [], progress: nil, completed: { (image, error, _, _, _) in
                            
                            print("原创微博单张图片下载完成")
                            
                            group.leave()

                        })
                        
                    }
                    
                }
                
                //判断转发微博当中配图的个数
                if model.statuses?.retweeted_status?.pic_urls?.count == 1{
                    
                    if let imageUrl = model.statuses?.retweeted_status?.pic_urls?.first?.thumbnail_pic {
                        
                        //进组
                        group.enter()
                        
                        SDWebImageManager.shared().downloadImage(with: URL(string:imageUrl), options: [], progress: nil, completed: { (image, error, _, _, _) in
                            
                            print("转发微博单张图片下载完成")
                            //退组
                            group.leave()

                        })
                        
                        
                    }
                }
                
            }
            
             //返回信息
            var message = ""
            
            if isPullUp{
                //上拉加载
                print("获取老微博成功")
                
               self.statuesList.append(contentsOf: modelArr)
            }else{
                //下拉刷新
                print("获取最新微博成功")

                self.statuesList.insert(contentsOf: modelArr, at: 0)
                
                
                if modelArr.count > 0{
                    
                    message = "更新了\(modelArr.count)条微博"
                }else{
                    
                    message = "没有最新的微博可更新"
                }
            }
            
            //当调度组内所有任务完成之后,会调用这个方法
            group.notify(queue: DispatchQueue.main, execute: {
                print("所有单张图片下载完毕")
                complete(true,message)
            })
            
            
        }
        
    }
}
